package ch.uzh.ifi.seal.ssqa.metrics.keyvalue;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;

import org.eclipse.emf.ecore.EObject;

import ch.uzh.ifi.seal.ssqa.model.Component;
import ch.uzh.ifi.seal.ssqa.model.DiagramComponent;
import ch.uzh.ifi.seal.ssqa.model.Module;
import ch.uzh.ifi.seal.ssqa.model.Source;
import ch.uzh.ifi.seal.ssqa.storage.IStorage;
import ch.uzh.ifi.seal.ssqa.storage.StorageResult;
import ch.uzh.ifi.seal.ssqa.storage.TeneoHibernateStorage;

public class DeveloperResponsabilityKeyValueMetric implements IKeyValueMetric{

	HashMap<Integer, Integer> userChanges = new HashMap<Integer, Integer>();

	private IStorage storage;

	public DeveloperResponsabilityKeyValueMetric readOutData(EObject object) {
		this.storage = new TeneoHibernateStorage();
		if (object instanceof DiagramComponent) {

		} else if (object instanceof Component) {
			this.readOutComponent((Component) object);
		}
		return this;
	}

	private void readOutComponent(Component component) {
		String path = "";
		if (component instanceof Source) {
			Source source = (Source) component;
			path = source.getProjectPath();
		} else if (component instanceof Module) {
			Module module = (Module) component;
			path = module.getProjectPath();
		}

		if (path != "") {
			StorageResult result = this.storage
					.executeListSQLQuery("SELECT issue.person_owner_e_id, revision.filepath FROM `ssqa`.`issue` as issue "
							+ " JOIN `ssqa`.`revision` as revision on issue.id = revision.ucmactivity_ucmactivity_e_id"
							+ " WHERE revision.filepath = '" + path + "'");

			List<Object[]> resultList = (List<Object[]>) result.getListResult();

			for (Object[] object : resultList) {
				int personId = ((BigInteger)object[0]).intValue();
				if (this.userChanges.containsKey(personId)) {
					int count = this.userChanges.get(personId) + 1;
					this.userChanges.put(personId, count);
				} else {
					this.userChanges.put(personId, 1);
				}
			}
			result.getSession().close();
		}
	}

	public HashMap<Integer, Integer> getResult() {
		return this.userChanges;
	}
}
